//
//  NetworkingHandle.m
//  PetAPP
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "NetworkingHandle.h"
#import "Reachability.h"
#import <CommonCrypto/CommonDigest.h>

#define FILE(STR) [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.da", STR]]


@implementation NetworkingHandle

+ (void)handleWorkData:(NSString *)URL AndBody:(NSString *)body value:(NSDictionary *)valueDic handleBlock:(void (^)(id result))block {
  
#pragma mark - 判断网络状态
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        /** url转码防止有汉字 */
        NSString *str = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        /** 创建url*/
        NSURL *url = [NSURL URLWithString:str];
        /** 创建可变请求 */
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        if (body == nil) {
            /** 方法post */
            request.HTTPMethod = @"GET";
            /** body如果是get可为空 */
            request.HTTPBody = nil;
        }else {
            /** 方法post */
            request.HTTPMethod = @"POST";
            /** body如果是get可为空 */
            request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
            
        }
        if (valueDic != nil) {
            for (NSString *key in valueDic) {
                [request addValue:[valueDic objectForKey:key] forHTTPHeaderField:key];
            }
        }
        
        /** 创建连接通道 */
        NSURLSession *session = [NSURLSession sharedSession];
        /** 创建任务 */
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSString *str = [NetworkingHandle md5HexDigest:[NSString stringWithFormat:@"%@+%@", URL, body]];
            
            
            /** 写入 */
            [data writeToFile:FILE(str) atomically:YES];
            NSError *errorJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
            dispatch_async(dispatch_get_main_queue(), ^{
                block(result);
            });
            
        }];
        /** 开始任务 */
        [task resume];
    }else {
        
        NSString *str = [NetworkingHandle md5HexDigest:[NSString stringWithFormat:@"%@+%@", URL, body]];
        NSData *data = [NSData dataWithContentsOfFile:FILE(str)];
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        block(result);

    }
    

}


+ (void)handlePassWord:(NSString *)URL AndBody:(NSString *)body value:(NSDictionary *)valueDic handleBlock:(void (^)(id result))block {
    
#pragma mark - 判断网络状态
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        /** url转码防止有汉字 */
        NSString *str = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        /** 创建url*/
        NSURL *url = [NSURL URLWithString:str];
        /** 创建可变请求 */
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        if (body == nil) {
            /** 方法post */
            request.HTTPMethod = @"GET";
            /** body如果是get可为空 */
            request.HTTPBody = nil;
        }else {
            /** 方法post */
            request.HTTPMethod = @"POST";
            /** body如果是get可为空 */
            request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
        }
        if (valueDic != nil) {
            for (NSString *key in valueDic) {
                [request addValue:[valueDic objectForKey:key] forHTTPHeaderField:key];
            }
        }
        
        /** 创建连接通道 */
        NSURLSession *session = [NSURLSession sharedSession];
        /** 创建任务 */
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSString *str = [NetworkingHandle md5HexDigest:[NSString stringWithFormat:@"%@+%@", URL, body]];
            /** 写入 */
            [data writeToFile:FILE(str) atomically:YES];
            
            NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            NSString *gbk = [[NSString alloc] initWithData:data encoding:gbkEncoding];
            
            NSData *data1 = [gbk dataUsingEncoding:NSUTF8StringEncoding];
            
            NSError *errorJSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:&errorJSON];
            dispatch_async(dispatch_get_main_queue(), ^{
                block(result);
            });
            
        }];
        /** 开始任务 */
        [task resume];
    }else {
        
        NSString *str = [NetworkingHandle md5HexDigest:[NSString stringWithFormat:@"%@+%@", URL, body]];
        
        
        NSData *data = [NSData dataWithContentsOfFile:FILE(str)];
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        block(result);
        
    }
    
    
}


/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}

@end
